package com.class5.springboot.frame.repo.real.init;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.class5.springboot.frame.repo.exception.RepositoryException;
import com.class5.springboot.frame.repo.tool.xml.DbTableIndex;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;



public class DbAdapter {
    private List<DbTableAdapter> tables = null;
    private JdbcTemplate jt;
    private String schema;
    public DbAdapter(JdbcTemplate jt) {
        this.jt = jt;
    }
    public synchronized String getSchema() {
        if(schema != null) {
            return schema;
        }
        schema = jt.query("SELECT DATABASE();", new RowMapper<String>() {
            @Override
            public String mapRow(ResultSet rs, int rowNum) throws SQLException {
                return rs.getString(1);
            }
        }).get(0);
        return schema;
    }
    public synchronized List<DbTableAdapter> getTables(){
        if(tables != null) {
            return tables;
        }
        //linux mac区分大小写
        String sql = "select TABLE_SCHEMA, TABLE_NAME from information_schema.tables where table_schema='"+getSchema()
                +"' and table_type='BASE TABLE'";
        tables = jt.query(sql, new RowMapper<DbTableAdapter>() {
            @Override
            public DbTableAdapter mapRow(ResultSet rs, int rowNum) throws SQLException {
                DbTableAdapter da = new DbTableAdapter(rs.getString("TABLE_SCHEMA"), rs.getString("TABLE_NAME").toLowerCase(), jt);
                return da;
            }
        });
        return tables;
    }
    public boolean isInDb(String table) {
        for(DbTableAdapter a : getTables()) {
            if(a.getName().equals(table)) {
                return true;
            }
        }
        return false;
    }
    public List<String> getDbTableNames() {
        List<String> ls = new ArrayList<>();
        for(DbTableAdapter da : getTables()) {
            ls.add(da.getName());
        }
        return ls;
    }
    public DbTableAdapter getByName(String name) {
        for(DbTableAdapter da : getTables()) {
            if(da.getName().equalsIgnoreCase(name))
                return da;
        }
        throw new RepositoryException("数据库表" + name + "不存在");
    }
    public List<DbTableIndex> getIndexes(String tableName) {
        Map<String, DbTableIndex> map = new HashMap<>();
        jt.query("show keys from " + tableName, new RowMapper<DbTableIndex>() {
            @Override
            public DbTableIndex mapRow(ResultSet rs, int rowNum) throws SQLException {
                String pname = rs.getString("key_name").toLowerCase();
                if(pname.equals("primary")) {
                    return null;
                }
                DbTableIndex ind = map.get(rs.getString("key_name").toLowerCase());
                if(ind == null) {
                    ind = new DbTableIndex();
                    ind.setName(rs.getString("Key_name").toLowerCase());
                    map.put(ind.getName(), ind);
                }
                if(ind.getColumns() == null) {
                    ind.setColumns(new String[] {rs.getString("Column_name").toLowerCase()});
                }else {
                    List<String> ls2 = new ArrayList<>();
                    ls2.add(rs.getString("Column_name").toLowerCase());
                    ls2.addAll(Arrays.asList(ind.getColumns()));
                    ind.setColumns(ls2.toArray(new String[ls2.size()]));
                }
                ind.setType(rs.getBoolean("Non_unique")?"unique":"normal");
                return null;
            }
        });
        List<DbTableIndex> ls = new ArrayList<>();
        ls.addAll(map.values());
        return ls;
    }

}
